What is string-width?
The string-width npm package is used to calculate and return the visual width of a string - the number of columns required to display it. This is particularly useful when dealing with strings containing characters that may take up more than one column in terminals or monospaced fonts, such as emojis or certain international characters.
What are string-width's main functionalities?
Calculate string width
This feature calculates the visual width of a string. For example, an ASCII character has a width of 1, while many CJK characters have a width of 2. Emojis can also have a width of 2 or more.
const stringWidth = require('string-width');
console.log(stringWidth('古')); // 2
console.log(stringWidth('a')); // 1
console.log(stringWidth('👍')); // 2
Other packages similar to string-width
wcwidth
The wcwidth package is similar to string-width in that it provides functionality to determine the number of terminal column cells a wide-character string will occupy. It is based on the wcwidth() function defined in POSIX.1-2001 and POSIX.1-2008 which is used in Unix-based systems.
eastasianwidth
This package is designed to provide the functionality to determine the East Asian Width property as defined by Unicode. It can be used to figure out if a character is full-width, half-width, wide, narrow, ambiguous, or neutral. This is similar to string-width but focuses specifically on East Asian characters.
string-pixel-width
While string-width calculates the number of columns a string will take up in a monospaced font, string-pixel-width calculates the width of a string in pixels. This is useful for determining the actual rendered width of a string in a web page or an application with proportional fonts.
string-width
Get the visual width of a string - the number of columns required to display it
Some Unicode characters are fullwidth and use double the normal width. ANSI escape codes are stripped and doesn't affect the width.
Useful to be able to measure the actual width of command-line output.
Install
$ npm install string-width
Usage
const stringWidth = require('string-width');
stringWidth('古');
stringWidth('\u001b[1m古\u001b[22m');
stringWidth('a');
stringWidth('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007');
Related
License
MIT © Sindre Sorhus